package com.fcscs.cservice.client.main.configuration.interfaceCon;

import java.math.BigDecimal;
import java.util.List;

import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.fcscs.core.common.authority.CServiceAuthority;
import com.fcscs.core.common.authority.UserAuthority;
import com.fcscs.core.domain.IdNameModel;
import com.fcscs.core.domain.Property;
import com.fcscs.core.gwt.common.AsyncCallbackListener;
import com.fcscs.core.gwt.common.CoreConstants;
import com.fcscs.core.gwt.common.SessionContext;
import com.fcscs.core.gwt.common.ui.CenteredInfo;
import com.fcscs.core.gwt.common.ui.FcsFields.EasyClearCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.FormButton;
import com.fcscs.core.gwt.common.ui.FcsPanel;
import com.fcscs.cservice.client.common.CServiceConstants;
import com.fcscs.cservice.client.common.controller.CServiceCommonServiceController;
import com.fcscs.cservice.client.common.model.configuration.reservation.PropertyIdNameModelData;
import com.fcscs.cservice.domain.InterfaceConfig;
import com.fcscs.share.gwt.common.ShareGWTConstants;
import com.google.gwt.user.client.ui.Widget;



public class InterfaceConfigPanel extends FcsPanel {
	
	private VerticalPanel vp;
	
	private TextField<String> eWebServiceURLTextField;
	private TextField<String> eUsernameTextField; 
	private TextField<String> ePasswordTextField;
	
	private TextField<String> cConnectWebServiceURLTextField;
	private TextField<String> cConnectUsernameTextField; 
	private TextField<String> cConnectPasswordTextField;
	
	private TextField<String> uWebServiceURLTextField;
	private TextField<String> cServiceDeviceIDTextField; 
	private TextField<String> mServiceDeviceIDRangeTextField;
	private TextField<String> toTextField;
	
	private TextField<String> smtpServerTextField;
	private TextField<String> smtpAccountTextField;
	private TextField<String> smtpPasswordTextField;
	
	private TextField<String> logoutIdelTimePeriodTextField;
	
	private InterfaceConfig currentInterConf;
	
	private EasyClearCombobox<PropertyIdNameModelData> propCombox;
	private ListStore<PropertyIdNameModelData> propListStore;
	private List<IdNameModel<Property>> propGroupIdNames;
	
	private FieldSet fieldset1;
	private FieldSet fieldsetcconnect;
	private FieldSet fieldset2;
	private FieldSet fieldset3;
	private FieldSet fieldset4;

	private boolean isChange;
	
	private FormButton saveButton;
	
	
	public InterfaceConfigPanel(String id) {
		super(id);
	}

	@Override
	public void init() {
		vp = new VerticalPanel();
		vp.setId("InterfaceConfigPanel_vpPanel");
		vp.setSpacing(5);
		
		LayoutContainer lcx = new LayoutContainer();
		lcx.setId("InterfaceConfigPanel_lcx");
		lcx.setLayout(new ColumnLayout());
		
		Label propLabel = new Label(CoreConstants.CORE_CONSTANTS.property() + CoreConstants.REQURIED_FIELD_LABEL);
		propLabel.setId("InterfaceConfigPanel_propLabel");
		
		propListStore = new ListStore<PropertyIdNameModelData>();
		propCombox = new EasyClearCombobox<PropertyIdNameModelData>();
		propCombox.setId("InterfaceConfigPanel_propCombox");
//		propCombox.setFieldLabel(CoreConstants.CORE_CONSTANTS.property());
		propCombox.setWidth(200);
		propCombox.setDisplayField(CoreConstants.FULLTNAME);
		propCombox.setAllowBlank(false);
		propCombox.setForceSelection(true);
		propCombox.setTriggerAction(TriggerAction.ALL);
		propCombox.setStore(propListStore);
//		propCombox.addSelectionChangedListener(new SelectionChangedListener<PropertyIdNameModelData>(){
//			@Override
//			public void selectionChanged(SelectionChangedEvent<PropertyIdNameModelData> se) {
//				myClear();
//				CServiceCommonServiceController.getINSTANCE().getInterfaceConf(
//						propCombox.getValue().getEntity().getId(), 
//						new AsyncCallbackListener<InterfaceConfig>(){
//							@Override
//							public void onLogin(String username) {
//								CServiceCommonServiceController.getINSTANCE().getInterfaceConf(
//									SessionContext.getInstance().getPropertyId(),this);
//							}
//							@Override
//							public void onFailure(Throwable caught) {
//								MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
//										CoreConstants.CORE_CONSTANTS.systemError(), null);
//							}
//							@Override
//							public void onSuccess(InterfaceConfig result) {
//								if(null != result){
//									eWebServiceURLTextField.setValue(result.getEconnect_ws_url());
//									eUsernameTextField.setValue(result.getEconnect_username());
//									ePasswordTextField.setValue(result.getEconnect_passwd());
////									cWebServiceURLTextField.setValue(result.getCconnect_ws_url());
////									cUsernameTextField.setValue(result.getCconnect_username());
////									cPasswordTextField.setValue(result.getCconnect_passwd());
//									uWebServiceURLTextField.setValue(result.getUnicorn_ws_url());
//									cServiceDeviceIDTextField.setValue(result.getUnicorn_cservice_device_id());
//									mServiceDeviceIDRangeTextField.setValue(result.getUnicorn_mservice_device_id_from());
//									toTextField.setValue(result.getUnicorn_mservice_device_id_to());
//									smtpServerTextField.setValue(result.getEmail_smtp_server());
//									smtpAccountTextField.setValue(result.getEmail_smtp_account());
//									smtpPasswordTextField.setValue(result.getEmail_smtp_passwd());
//									logoutIdelTimePeriodTextField.setValue(result.getLogout_idle_time()+"");
//								}
//							}
//						});
//			}
//		});
		
		lcx.add(propLabel, new ColumnData(70));
		lcx.add(propCombox, new ColumnData(180));
		
		vp.add(lcx);
		
		FormPanel panel = new FormPanel();
		panel.setId("InterfaceConfigPanel_panel");
		panel.setFrame(true);
		panel.setHeading(CServiceConstants.CSERVICE_CONSTANTS.interfaceConf());
		panel.setPadding(10);
		panel.setSize(730, 500);
		panel.setScrollMode(Scroll.AUTOY);
		panel.setLabelAlign(LabelAlign.LEFT);
		panel.setLabelSeparator("");
		panel.setLabelWidth(180);
		panel.setFieldWidth(340);
		
		
		LayoutContainer lca = new LayoutContainer();
		lca.setId("InterfaceConfigPanel_lca");
//		lca.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "10px");
		FormLayout layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.LEFT);
		layout.setLabelWidth(180);
		layout.setDefaultWidth(340);
		layout.setLabelSeparator("");
		lca.setLayout(layout);
		lca.setBorders(false);
		
		fieldset1 = new FieldSet();
		fieldset1.setWidth(650);
		fieldset1.setId("ExpressCheckInConfigPanel_fieldset1");
		fieldset1.setHeading(CServiceConstants.CSERVICE_CONSTANTS.eConnect());
		fieldset1.add(lca);
	    panel.add(fieldset1);
        
        eWebServiceURLTextField = new TextField<String>();
        eWebServiceURLTextField.setId("InterfaceConfigPanel_eWebServiceURLTextField");
        eWebServiceURLTextField.setAllowBlank(false);
        eWebServiceURLTextField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.webServiceURL() + CServiceConstants.FIELD_SEP);
        eWebServiceURLTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.webServiceURL(), 255);
				}
				return null;
			}
        });
        eWebServiceURLTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!eWebServiceURLTextField.getValue().equals(currentInterConf.getEconnectWebServiceUrl()) || isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else {
					saveButton.setEnabled(false);
				}
			}
		});
        lca.add(eWebServiceURLTextField);
	    
	    eUsernameTextField = new TextField<String>();
	    eUsernameTextField.setId("InterfaceConfigPanel_eUsernameTextField");
	    eUsernameTextField.setAllowBlank(false);
	    eUsernameTextField.setFieldLabel(CoreConstants.CORE_CONSTANTS.username() + CServiceConstants.FIELD_SEP);
	    eUsernameTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CoreConstants.CORE_CONSTANTS.username(), 255);
				}
				return null;
			}
        });
	    eUsernameTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!eUsernameTextField.getValue().trim().equals(currentInterConf.getEconnectWebServiceUsername()) || isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else{
					saveButton.setEnabled(false);
				}
				
			}
		});
	    lca.add(eUsernameTextField);
	    
	    ePasswordTextField = new TextField<String>();
	    ePasswordTextField.setId("InterfaceConfigPanel_ePasswordTextField");
	    ePasswordTextField.setAllowBlank(false);
	    ePasswordTextField.setFieldLabel(CoreConstants.CORE_CONSTANTS.pwd() + CServiceConstants.FIELD_SEP);
	    ePasswordTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CoreConstants.CORE_CONSTANTS.pwd(), 255);
				}
				return null;
			}
        });
	    ePasswordTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!ePasswordTextField.getValue().trim().equals(currentInterConf.getEconnectWebServicePassword()) || isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lca.add(ePasswordTextField);
	    
	    LayoutContainer lccconnect = new LayoutContainer();
	    lccconnect.setId("InterfaceConfigPanel_lca");
//		lca.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "10px");
		FormLayout layout1 = new FormLayout();
		layout1.setLabelAlign(LabelAlign.LEFT);
		layout1.setLabelWidth(180);
		layout1.setDefaultWidth(340);
		layout1.setLabelSeparator("");
		lccconnect.setLayout(layout1);
		lccconnect.setBorders(false);
		
		fieldsetcconnect = new FieldSet();
		fieldsetcconnect.setWidth(650);
		fieldsetcconnect.setId("ExpressCheckInConfigPanel_fieldsetcconnect");
		fieldsetcconnect.setHeading(CServiceConstants.CSERVICE_CONSTANTS.cConnect());
		fieldsetcconnect.add(lccconnect);
	    panel.add(fieldsetcconnect);
        
        cConnectWebServiceURLTextField = new TextField<String>();
        cConnectWebServiceURLTextField.setId("InterfaceConfigPanel_cConnectWebServiceURLTextField");
        cConnectWebServiceURLTextField.setAllowBlank(false);
        cConnectWebServiceURLTextField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.webServiceURL() + CServiceConstants.FIELD_SEP);
        cConnectWebServiceURLTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.webServiceURL(), 255);
				}
				return null;
			}
        });
        cConnectWebServiceURLTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!cConnectWebServiceURLTextField.getValue().equals(currentInterConf.getCconnectWebServiceUrl()) || isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
        lccconnect.add(cConnectWebServiceURLTextField);
	    
	    cConnectUsernameTextField = new TextField<String>();
	    cConnectUsernameTextField.setId("InterfaceConfigPanel_cConnectUsernameTextField");
	    cConnectUsernameTextField.setAllowBlank(false);
	    cConnectUsernameTextField.setFieldLabel(CoreConstants.CORE_CONSTANTS.username() + CServiceConstants.FIELD_SEP);
	    cConnectUsernameTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CoreConstants.CORE_CONSTANTS.username(), 255);
				}
				return null;
			}
        });
	    cConnectUsernameTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!cConnectUsernameTextField.getValue().equals(currentInterConf.getCconnectWebServiceUsername()) || isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lccconnect.add(cConnectUsernameTextField);
	    
	    cConnectPasswordTextField = new TextField<String>();
	    cConnectPasswordTextField.setId("InterfaceConfigPanel_cConnectPasswordTextField");
	    cConnectPasswordTextField.setAllowBlank(false);
	    cConnectPasswordTextField.setFieldLabel(CoreConstants.CORE_CONSTANTS.pwd() + CServiceConstants.FIELD_SEP);
	    cConnectPasswordTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CoreConstants.CORE_CONSTANTS.pwd(), 255);
				}
				return null;
			}
        });
	    cConnectPasswordTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!cConnectPasswordTextField.getValue().equals(currentInterConf.getCconnectWebServicePassword())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lccconnect.add(cConnectPasswordTextField);
        
	    
	    
	    LayoutContainer lcb = new LayoutContainer();
	    lcb.setId("InterfaceConfigPanel_lcb");
		lcb.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "10px");
		layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.LEFT);
		layout.setLabelWidth(180);
		layout.setDefaultWidth(340);
		layout.setLabelSeparator("");
		lcb.setLayout(layout);
		lcb.setBorders(false);
		
		fieldset2 = new FieldSet();
		fieldset2.setWidth(650);
		fieldset2.setId("ExpressCheckInConfigPanel_fieldset1");
		fieldset2.setHeading(CServiceConstants.CSERVICE_CONSTANTS.ubisUnicorn());
		fieldset2.add(lcb);
	    panel.add(fieldset2);
        
        uWebServiceURLTextField = new TextField<String>();
        uWebServiceURLTextField.setId("InterfaceConfigPanel_uWebServiceURLTextField");
        uWebServiceURLTextField.setAllowBlank(false);
        uWebServiceURLTextField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.webServiceURL() + CServiceConstants.FIELD_SEP);
        uWebServiceURLTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.webServiceURL(), 255);
				}
				return null;
			}
        });
        uWebServiceURLTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!uWebServiceURLTextField.getValue().equals(currentInterConf.getUbisWebServiceUrl())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
        lcb.add(uWebServiceURLTextField);
	    
	    cServiceDeviceIDTextField = new TextField<String>();
	    cServiceDeviceIDTextField.setId("InterfaceConfigPanel_cServiceDeviceIDTextField");
	    cServiceDeviceIDTextField.setAllowBlank(false);
	    cServiceDeviceIDTextField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.cServiceDeviceID() + CServiceConstants.FIELD_SEP);
	    cServiceDeviceIDTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.cServiceDeviceID(), 255);
				}
				return null;
			}
        });
	    cServiceDeviceIDTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!cServiceDeviceIDTextField.getValue().equals(currentInterConf.getUbisCserviceDeviceId())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lcb.add(cServiceDeviceIDTextField);
	    
	    LayoutContainer lc = new LayoutContainer();
	    lc.setId("InterfaceConfigPanel_lc");
	    lc.setLayout(new ColumnLayout());
	    
//	    Label myLabel = new Label("<html><font size=\"2\">" 
//	    		+ CServiceConstants.CSERVICE_CONSTANTS.mserviceDeviceIDRange() + CServiceConstants.FIELD_SEP
//	    		+ "</font></html>");
//	    myLabel.setId("InterfaceConfigPanel_myLabel");
//	    lc.add(myLabel, new ColumnData(185));
	    
	    Label myLabel = new Label(CServiceConstants.CSERVICE_CONSTANTS.mserviceDeviceIDRange() + CServiceConstants.FIELD_SEP);
	    myLabel.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "2px");
	    lc.add(myLabel, new ColumnData(185));
	    
	    mServiceDeviceIDRangeTextField = new TextField<String>();
	    mServiceDeviceIDRangeTextField.setId("InterfaceConfigPanel_mServiceDeviceIDRangeTextField");
	    mServiceDeviceIDRangeTextField.setAllowBlank(false);
	    mServiceDeviceIDRangeTextField.setEmptyText(CoreConstants.CORE_CONSTANTS.from());
	    mServiceDeviceIDRangeTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.mServiceDeviceID(), 255);
				}
				return null;
			}
        });
	    mServiceDeviceIDRangeTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!mServiceDeviceIDRangeTextField.getValue().equals(currentInterConf.getUbisMserviceDeviceIdFrom())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lc.add(mServiceDeviceIDRangeTextField, new ColumnData(170));
	    
	    toTextField = new TextField<String>();
	    toTextField.setId("InterfaceConfigPanel_toTextField");
	    toTextField.setAllowBlank(false);
	    toTextField.setFieldLabel("");
	    toTextField.setEmptyText(CoreConstants.CORE_CONSTANTS.to());
	    toTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.mServiceDeviceID(), 255);
				}
				return null;
			}
        });
	    toTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!toTextField.getValue().equals(currentInterConf.getUbisMserviceDeviceIdTo())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lc.add(toTextField, new ColumnData(170));
	    lcb.add(lc);
	    
	    LayoutContainer lcc = new LayoutContainer();
	    lcc.setId("InterfaceConfigPanel_lcc");
	    lcc.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "10px");
		layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.LEFT);
		layout.setLabelWidth(180);
		layout.setDefaultWidth(340);
		layout.setLabelSeparator("");
		lcc.setLayout(layout);
		lcc.setBorders(false);
	    
	    fieldset3 = new FieldSet();
		fieldset3.setWidth(650);
		fieldset3.setId("ExpressCheckInConfigPanel_fieldset3");
		fieldset3.setHeading(CServiceConstants.CSERVICE_CONSTANTS.emailAccount());
		fieldset3.add(lcc);
	    panel.add(fieldset3);
        
        smtpServerTextField = new TextField<String>();
        smtpServerTextField.setId("InterfaceConfigPanel_smtpServerTextField");
        smtpServerTextField.setAllowBlank(false);
        smtpServerTextField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.smtpServer() + CServiceConstants.FIELD_SEP);
        smtpServerTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.smtpServer(), 255);
				}
				return null;
			}
        });
        smtpServerTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!smtpServerTextField.getValue().equals(currentInterConf.getEmailSmtpServer())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
        lcc.add(smtpServerTextField);
	    
	    smtpAccountTextField = new TextField<String>();
	    smtpAccountTextField.setId("InterfaceConfigPanel_smtpAccountTextField");
	    smtpAccountTextField.setAllowBlank(false);
	    smtpAccountTextField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.smtpAccount() + CServiceConstants.FIELD_SEP);
	    smtpAccountTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CServiceConstants.CSERVICE_CONSTANTS.smtpAccount(), 255);
				}
				return null;
			}
        });
	    smtpAccountTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!smtpAccountTextField.getValue().equals(currentInterConf.getEmailSmtpAccount())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lcc.add(smtpAccountTextField);
	    
	    smtpPasswordTextField = new TextField<String>();
	    smtpPasswordTextField.setId("InterfaceConfigPanel_smtpPasswordTextField");
	    smtpPasswordTextField.setAllowBlank(false);
	    smtpPasswordTextField.setFieldLabel(CoreConstants.CORE_CONSTANTS.pwd() + CServiceConstants.FIELD_SEP);
	    smtpPasswordTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value != null 
				   && !value.trim().isEmpty()
				   && value.trim().length() > 255){
					return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(
							CoreConstants.CORE_CONSTANTS.pwd(), 255);
				}
				return null;
			}
        });
	    smtpPasswordTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!smtpPasswordTextField.getValue().equals(currentInterConf.getEmailPassword())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lcc.add(smtpPasswordTextField);
	    
	    LayoutContainer lcd = new LayoutContainer();
	    lcd.setId("InterfaceConfigPanel_lcd");
	    lcd.setStyleAttribute(CServiceConstants.CSS_MARGINTOP, "10px");
		layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.LEFT);
		layout.setLabelWidth(180);
		layout.setDefaultWidth(340);
		layout.setLabelSeparator("");
		lcd.setLayout(layout);
		lcd.setBorders(false);
	    
	    fieldset4 = new FieldSet();
	    fieldset4.setWidth(650);
	    fieldset4.setId("ExpressCheckInConfigPanel_fieldset4");
	    fieldset4.setHeading(CServiceConstants.CSERVICE_CONSTANTS.emailAccount());
	    fieldset4.add(lcd);
	    panel.add(fieldset4);
        
	    logoutIdelTimePeriodTextField = new TextField<String>();
	    logoutIdelTimePeriodTextField.setId("InterfaceConfigPanel_logoutIdelTimePeriodTextField");
	    logoutIdelTimePeriodTextField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.logoutIdleTimerPeriod() + CoreConstants.REQURIED_FIELD_LABEL);
	    logoutIdelTimePeriodTextField.setAllowBlank(false);
	    logoutIdelTimePeriodTextField.setValidator(new Validator(){
			@Override
			public String validate(Field<?> field, String value) {
				if(value == null){
					return CoreConstants.CORE_CONSTANTS.requiredField();
				}else if(value.trim().isEmpty()){
					return ShareGWTConstants.SHARE_GWT_CONSTANTS.cannotEmpty();
				}else if(!isValidNum(value.trim())){
					return CServiceConstants.CSERVICE_MESSAGES.enterNumBetweenAnd("1", "1440");
				}
				return null;
			}
	    });
	    logoutIdelTimePeriodTextField.addListener(Events.OnBlur, new Listener<BaseEvent>(){
			@Override
			public void handleEvent(BaseEvent be) {
				String value = logoutIdelTimePeriodTextField.getValue();
				if(value == null){
					logoutIdelTimePeriodTextField.forceInvalid(CoreConstants.CORE_CONSTANTS.requiredField());
					return;
				}else if(value.trim().isEmpty()){
					logoutIdelTimePeriodTextField.forceInvalid(ShareGWTConstants.SHARE_GWT_CONSTANTS.cannotEmpty());
					return;
				}else if(!isValidNum(value.trim())){
					logoutIdelTimePeriodTextField.forceInvalid(CServiceConstants.CSERVICE_MESSAGES.enterNumBetweenAnd("1", "1440"));
					return;
				}else{
					logoutIdelTimePeriodTextField.clearInvalid();
					return;
				}
			}
	    });
	    logoutIdelTimePeriodTextField.addListener(Events.KeyUp, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				// TODO Auto-generated method stub
				if(!logoutIdelTimePeriodTextField.getValue().equals(currentInterConf.getLogoutIdleTimerPeriod())||isChange){
					saveButton.setEnabled(true);
					isChange=true;
				}
				else
					saveButton.setEnabled(false);
			}
		});
	    lcd.add(logoutIdelTimePeriodTextField);
		
        vp.add(panel);
	    
	    saveButton = new FormButton(CoreConstants.CORE_CONSTANTS.save());
	    saveButton.setId("InterfaceConfigPanel_saveButton");
	    saveButton.setStyleAttribute(CServiceConstants.CSS_MARGINLEFT, "560px");
	    saveButton.setEnabled(false);
		saveButton.setSize(60, 30);
		saveButton.addSelectionListener(new SelectionListener<ButtonEvent>(){
			@Override
			public void componentSelected(ButtonEvent ce) {
				if(eWebServiceURLTextField.isValid()
				   && eUsernameTextField.isValid()
				   && ePasswordTextField.isValid()
				   && cConnectWebServiceURLTextField.isValid()
				   && cConnectUsernameTextField.isValid()
				   && cConnectPasswordTextField.isValid()
				   && uWebServiceURLTextField.isValid()
				   && cServiceDeviceIDTextField.isValid()
				   && mServiceDeviceIDRangeTextField.isValid()
				   && toTextField.isValid()
				   && smtpServerTextField.isValid()
				   && smtpAccountTextField.isValid()
				   && smtpPasswordTextField.isValid()
				   && logoutIdelTimePeriodTextField.isValid()){
					
						currentInterConf.setEconnectWebServiceUrl(eWebServiceURLTextField.getValue() == null ? null : eWebServiceURLTextField.getValue().trim());
						currentInterConf.setEconnectWebServiceUsername(eUsernameTextField.getValue() == null ? null : eUsernameTextField.getValue().trim());
						currentInterConf.setEconnectWebServicePassword(ePasswordTextField.getValue() == null ? null : ePasswordTextField.getValue().trim());
						currentInterConf.setCconnectWebServiceUrl(cConnectWebServiceURLTextField.getValue() == null ? null : cConnectWebServiceURLTextField.getValue().trim());
						currentInterConf.setCconnectWebServiceUsername(cConnectUsernameTextField.getValue() == null ? null : cConnectUsernameTextField.getValue().trim());
						currentInterConf.setCconnectWebServicePassword(cConnectPasswordTextField.getValue() == null ? null : cConnectPasswordTextField.getValue().trim());
						currentInterConf.setUbisWebServiceUrl(uWebServiceURLTextField.getValue() == null ? null : uWebServiceURLTextField.getValue().trim());
						currentInterConf.setUbisCserviceDeviceId(cServiceDeviceIDTextField.getValue() == null ? null : cServiceDeviceIDTextField.getValue().trim());
						currentInterConf.setUbisMserviceDeviceIdFrom(mServiceDeviceIDRangeTextField.getValue() == null ? null : mServiceDeviceIDRangeTextField.getValue().trim());
						currentInterConf.setUbisMserviceDeviceIdTo(toTextField.getValue() == null ? null : toTextField.getValue().trim());
						currentInterConf.setEmailSmtpServer(smtpServerTextField.getValue() == null ? null : smtpServerTextField.getValue().trim());
						currentInterConf.setEmailSmtpAccount(smtpAccountTextField.getValue() == null ? null : smtpAccountTextField.getValue().trim());
						currentInterConf.setEmailPassword(smtpPasswordTextField.getValue() == null ? null : smtpPasswordTextField.getValue().trim());
						currentInterConf.setLogoutIdleTimerPeriod(Integer.parseInt(logoutIdelTimePeriodTextField.getValue().trim()));
						
						CServiceCommonServiceController.getINSTANCE().saveInterfaceConfig(
							currentInterConf, new AsyncCallbackListener<InterfaceConfig>(){
								@Override
								public void onLogin(String username) {
									CServiceCommonServiceController.getINSTANCE().saveInterfaceConfig(
										currentInterConf, this);
								}
								@Override
								public void onFailure(Throwable caught) {
									MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
										CoreConstants.CORE_CONSTANTS.systemError(), null);
								}
								@Override
								public void onSuccess(InterfaceConfig result) {
									if(null != result){
										CenteredInfo.displayCompleted(CoreConstants.CORE_CONSTANTS.edited());
									}
								}
						});
						saveButton.setEnabled(false);
						isChange=false;
					}
				
//				try {
//		            OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));
//		 
//		            Document document = new Document();
//		            PdfWriter.getInstance(document, file);
//		 
//		            document.open();
//		            document.add(new Paragraph("Hello World, iText"));
//		            document.add(new Paragraph(new Date().toString()));
//		 
//		            document.close();
////		            file.close();
//		 
//		        } catch (Exception e) {
//		 
//		            e.printStackTrace();
//		        }
			}
		});
		
		vp.add(saveButton);
		
	    add(vp);
		
        onShow();
	}

	@Override
	public UserAuthority getRequiredAuthority() {
		return CServiceAuthority.cSERVICE_CONFIG;
	}

	@Override
	protected Widget getViewPanel() {
		return vp;
	}

	@Override
	public void onShow() {
		loadProperty();
		myClear();
		CServiceCommonServiceController.getINSTANCE().getInterfaceConfig(
			SessionContext.getInstance().getPropertyId(), 
			new AsyncCallbackListener<InterfaceConfig>(){
				@Override
				public void onLogin(String username) {
					CServiceCommonServiceController.getINSTANCE().getInterfaceConfig(
						SessionContext.getInstance().getPropertyId(),this);
				}
				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
							CoreConstants.CORE_CONSTANTS.systemError(), null);
				}
				@Override
				public void onSuccess(InterfaceConfig result) {
					if(null != result){
						
						currentInterConf = result;
						
						eWebServiceURLTextField.setValue(result.getEconnectWebServiceUrl());
						eUsernameTextField.setValue(result.getEconnectWebServiceUsername());
						ePasswordTextField.setValue(result.getEconnectWebServicePassword());
						cConnectWebServiceURLTextField.setValue(result.getCconnectWebServiceUrl());
						cConnectUsernameTextField.setValue(result.getCconnectWebServiceUsername());
						cConnectPasswordTextField.setValue(result.getCconnectWebServicePassword());
						uWebServiceURLTextField.setValue(result.getUbisWebServiceUrl());
						cServiceDeviceIDTextField.setValue(result.getUbisCserviceDeviceId());
						mServiceDeviceIDRangeTextField.setValue(result.getUbisMserviceDeviceIdFrom());
						toTextField.setValue(result.getUbisMserviceDeviceIdTo());
						smtpServerTextField.setValue(result.getEmailSmtpServer());
						smtpAccountTextField.setValue(result.getEmailSmtpAccount());
						smtpPasswordTextField.setValue(result.getEmailPassword());
						logoutIdelTimePeriodTextField.setValue(result.getLogoutIdleTimerPeriod()+"");
						
//						currenteWebServiceURLTextField = result.getEconnectWebServiceUrl();
//						currenteUsernameTextField = result.getEconnectWebServiceUsername();
//						currentePasswordTextField =result.getEconnectWebServicePassword();
//						currentcConnectWebServiceURLTextField=result.getCconnectWebServiceUrl();
//						currentcConnectUsernameTextField=result.getCconnectWebServiceUsername();
//						currentcConnectPasswordTextField=result.getCconnectWebServicePassword();
//						currentuWebServiceURLTextField=result.getUbisWebServiceUrl();
//						currentcServiceDeviceIDTextField=result.getUbisCserviceDeviceId();
//						currentmServiceDeviceIDRangeTextField=result.getUbisMserviceDeviceIdFrom();
//						currenttoTextField=result.getUbisMserviceDeviceIdTo();
//						currentsmtpServerTextField=result.getEmailSmtpServer();
//						currentsmtpAccountTextField=result.getEmailSmtpAccount();
//						currentsmtpPasswordTextField=result.getEmailPassword();
//						currentlogoutIdelTimePeriodTextField=result.getLogoutIdleTimerPeriod()+"";
					}
				}
			});
	}

	@Override
	public boolean onHide() {
		myClear();
		return true;
	}
	
//	private void generatePDF(){
//		
////		ArrayCollection dataProvider = ArrayCollection.newInstance();
////		dataProvider.addItem(currentInterConf.getEconnectWebServiceUrl(), currentInterConf.getEconnectWebServiceUsername(), currentInterConf.getEconnectWebServicePassword());
//		
//		
//		GridColumn eULRColumn = GridColumn.newInstance("eConnect ULR", "eULR", 50, Align.CENTER);  
//        GridColumn eUsernameColumn = GridColumn.newInstance("eConnect Username", "eUsername", 50, Align.CENTER);  
//        GridColumn ePasswordColumn = GridColumn.newInstance("eConnect Password", "ePassword", 50, Align.CENTER);
//        JsArray<GridColumn> columns = JsArray.createArray().cast();
//        
//        
//        columns.push(eULRColumn);  
//        columns.push(eUsernameColumn);  
//        columns.push(ePasswordColumn);
//        
//        Grid grid = null;
//        
////        Grid grid = Grid.newInstance(("than", "than1", "than3"), //data  
////                250, //width  
////                300, //height  
////                RGBColor.newInstance(0xE6E6FA), //headerColor  
////                RGBColor.newInstance(0xF5FFFA), //cellcolor  
////                true, //userAlternateRowColor  
////                RGBColor.newInstance(0x00FA9A), //alternateRowColor  
////                RGBColor.newInstance(0x1E90FF), // borderColor  
////                1, // borderAlpha  
////                10 // headerHeight  
////                );  
//        
//        
//        grid.setColumns(columns);  
//        PDF pdf = PDF.newInstance();
//        pdf.addPage();
//        pdf.setTextStyle(RGBColor.newInstance(0x000000));  
//        pdf.setFont(CoreFont.newInstance(FontFamily.ARIAL), 10);  
//        pdf.addGrid(grid);  
//  
//        ByteArray data = pdf.save();  
//  
//        Application.get().saveFile(data, "X-Men.pdf");
//	}

	private void myClear() {
		eWebServiceURLTextField.clear();
		eUsernameTextField.clear();
		ePasswordTextField.clear();
//		cConnectWebServiceURLTextField.clear();
//		cConnectUsernameTextField.clear();
//		cConnectPasswordTextField.clear();
		uWebServiceURLTextField.clear();
		cServiceDeviceIDTextField.clear();
		mServiceDeviceIDRangeTextField.clear();
		toTextField.clear();
		smtpServerTextField.clear();
		smtpAccountTextField.clear();
		smtpPasswordTextField.clear();
		logoutIdelTimePeriodTextField.clear();
	}

	private boolean isValidNum(String minutes){
		boolean isValid = true;
		for(int i = 0; i < minutes.length() ; i++){
			if(!Character.isDigit(minutes.charAt(i))){
				isValid = false;
				break;
			}
		}
		BigDecimal bd = new BigDecimal(minutes);
		if(isValid && ((bd.compareTo(new BigDecimal(Integer.valueOf(1440))) == 1)
			       || (bd.compareTo(new BigDecimal(Integer.valueOf(1))) == -1))){
			isValid = false;
		}
		return isValid;
	}

	@Override
	public void setFocus() {
		eWebServiceURLTextField.focus();
	}
	
	private void loadProperty() {
		propGroupIdNames = SessionContext.getInstance().getPropertyGroup();
		propListStore.removeAll();
		if (0 != propGroupIdNames.size()) {
			int propIndex = 0;
			for (IdNameModel<Property> inm : propGroupIdNames) {
				propListStore.add(new PropertyIdNameModelData(inm));
				if (propIndex == 0) {
					if (SessionContext.getInstance().getPropertyId() == inm.getId()) {
						propIndex = propListStore.getCount() - 1;
					}
				}
			}
			propCombox.setValue(propListStore.getAt(propIndex));
		} else {
			IdNameModel<Property> tempINM = new IdNameModel<Property>(SessionContext.getInstance().getPropertyId(), SessionContext.getInstance().getPropertyName());
			propListStore.add(new PropertyIdNameModelData(tempINM));
			propCombox.setValue(propListStore.getAt(0));
		}
//		propListStore.removeAll();
//		IdNameModel<Property> tempINM = new IdNameModel<Property>(SessionContext.getInstance().getPropertyId(), SessionContext.getInstance().getPropertyName());
//		propListStore.add(new PropertyIdNameModelData(tempINM));
//		propCombox.setValue(propListStore.getAt(0));
//		grid.setCurrentProperty(propListStore.getAt(0));
	}
}
